package com.lzb.newloan;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzb.newloan.adapter.InvestAdapter;
import com.lzb.newloan.pojo.BorrowPersonPojo;
import com.lzb.newloan.utils.ActionSheetDialog;
import com.lzb.newloan.utils.ActionSheetDialog.OnSheetItemClickListener;
import com.lzb.newloan.utils.ActionSheetDialog.SheetItemColor;
import com.lzb.newloan.utils.AlertDialog;
import com.lzb.newloan.utils.BaseApplication;
import com.lzb.newloan.utils.Config;
import com.lzb.newloan.utils.HttpUtils;
import com.lzb.newloan.utils.TimeUtils;
import com.lzb.newloan.xlistview.XListView;
import com.lzb.newloan.xlistview.XListView.IXListViewListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * touziliebiao
 */
public class InvestFragment extends Fragment implements IXListViewListener,InvestAdapter.CheckInterface {

	private View view;
	private TextView money_select, sex_select;
	private XListView invest_list;
	private int curPage = 1,num = 0,count;
	private boolean isloadMore;
	private ImageView img;
	private ArrayList<BorrowPersonPojo> arrayList;
	private InvestAdapter adapter;
	private LinearLayout filter;
	private ImageView empty;
	private String sexperson="";
	private String minmoney="";
	private String maxmoney="";
	private String userId,event_total_key="";
	private int title_right_txt;
	private BaseApplication app;
	private TextView title_txt_center;

	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (view == null) {
			view = inflater.inflate(R.layout.fragment_invest, null);
			intView();
			initData(minmoney,maxmoney,sexperson);
		} else {
			((ViewGroup) view.getParent()).removeView(view);
		}
		return view;
	}



	public void getFive(){
		AlertDialog ad = new AlertDialog(getActivity());
		ad.builder();
		ad.setMsg("您已选取了5人进行投资，请问是否马上支付？");
		ad.setNegativeButton("再选选", new View.OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		});
		ad.setPositiveButton("立即支付", new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String str = "";
				for (int i = 0; i < arrayList.size(); i++) {
					BorrowPersonPojo pojo = arrayList.get(i);
					if(pojo.isChecked()){
						if (str.equals("")){
							str=pojo.getJkid();
						}else{
							str=str+","+pojo.getJkid();
						}
					}
				}

				Intent intent = new Intent(getActivity(), com.lzb.newloan.InvestPersonPayActivity.class);
				intent.putExtra("jkid", str);
				getActivity().startActivity(intent);
			}
		});
		ad.show();

	}

	/**
	 * 单选
	 *
	 * @param position  组元素位置
	 * @param isChecked 组元素选中与否
	 */
	@Override
	public void checkGroup(int position, boolean isChecked) {
		if(count<5){
			adapter.getArrayList().get(position).setChecked(isChecked);
			adapter.notifyDataSetChanged();
			statistics();
			if(count==5){
						getFive();
			}
		}else{
			adapter.getArrayList().get(position).setChecked(false);
			adapter.notifyDataSetChanged();
			getFive();
		}
	}


	/**
	 * 统计操作
	 * 1.先清空全局计数器<br>
	 * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
	 * 3.给底部的textView进行数据填充
	 */
	public void statistics() {
		num = 0;
		for (int i = 0; i < adapter.getArrayList().size(); i++) {
			BorrowPersonPojo pojo = adapter.getArrayList().get(i);
			if (num >= 5) {

				break;
			} else {
				if (pojo.isChecked()) {
					num++;
				}
			}
		}
		count = num;
		title_txt_center.setText("已选择 " + num + "/5");
	}


	private void initData(String minLoan_amount,String  maxLoan_amount,String gender) {

		HttpUtils.doPostAsyn(Config.BORROWPERSON_CORD +"&userid="+userId+"&curPage="
				+ curPage+"&gender="+gender+"&minLoan_amount="+minmoney+"&maxLoan_amount="+maxmoney,"", mHandler, Config.CODE_BORROWPERSON);

	}

	private Handler mHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case Config.CODE_URL_ERROR:
					Toast.makeText(getActivity(), "url错误",
							Toast.LENGTH_SHORT).show();
					break;
				case Config.CODE_NET_ERROR:
					Toast.makeText(getActivity(), "网络错误",
							Toast.LENGTH_SHORT).show();
					break;
				case Config.CODE_BORROWPERSON:
					String result = msg.obj.toString();
					try {
						JSONObject response = new JSONObject(result);
						try {
							if (response != null) {
								int totalPages = response.getInt("totalPages");
								if (totalPages==0) {
									empty.setVisibility(View.VISIBLE);
									invest_list.setVisibility(View.GONE);
								}else {
									empty.setVisibility(View.GONE);
									invest_list.setVisibility(View.VISIBLE);
									if (curPage < totalPages) {
										invest_list.setPullLoadEnable(true);
									} else {
										invest_list.setPullLoadEnable(false);
									}
									JSONArray dataArray = response.getJSONArray("list");
									ArrayList<BorrowPersonPojo> arrayList2 = new ArrayList<BorrowPersonPojo>();
									if (dataArray.length() != 0) {
										for (int i = 0; i < dataArray.length(); i++) {
											BorrowPersonPojo pojo = new BorrowPersonPojo();
											JSONObject object = dataArray.getJSONObject(i);
											pojo.setUsername(object.getString("name"));
											pojo.setLiving_photo(object.optString("living_photo"));
											pojo.setJkid(object.optString("jkid"));
											int jkqx = object.optInt("jkqx");
											if (jkqx == 1) {
												pojo.setTime("15天");
											} else {
												pojo.setTime("30天");
											}
											double highMoney = object.optDouble("annual_rate");
											double money = Double.parseDouble(object.optString("sjsh_money"));
											pojo.setFk_money(highMoney);
											pojo.setJk_money(money);
											pojo.setSex(object.optInt("gender"));
											arrayList2.add(pojo);
										}
									}
									if (isloadMore) {
										arrayList.addAll(arrayList2);
									} else {
										arrayList = arrayList2;
									}

									adapter.setArrayList(arrayList);
									adapter.notifyDataSetChanged();

								}

							} else {
								empty.setVisibility(View.VISIBLE);
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} catch (JSONException e) {
						Toast.makeText(getActivity(), "数据解析错误",
								Toast.LENGTH_SHORT).show();
						e.printStackTrace();
					}

					break;

				default:
					break;
			}
		};
	};

	private void intView() {
		img = (ImageView) view.findViewById(R.id.img);
		SharedPreferences sp = getActivity().getSharedPreferences("config", 0x0000);
		userId = sp.getString("userid", "");
		app = (BaseApplication) getActivity().getApplicationContext();
		RelativeLayout backpress = (RelativeLayout) view
				.findViewById(R.id.backpress);
		backpress.setVisibility(View.INVISIBLE);
		title_txt_center = (TextView) view
				.findViewById(R.id.title_txt_center);
		title_txt_center.setText("已选择  0/5");

		TextView title_right_txt = (TextView) view.findViewById(R.id.title_right_txt);
		title_right_txt.setVisibility(View.VISIBLE);
		title_right_txt.setText("立即支付");
		title_right_txt.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				String str = "";
				for (int i = 0;i<adapter.getArrayList().size();i++){
					BorrowPersonPojo pojo = arrayList.get(i);
					if(pojo.isChecked()){
						if (str.equals("")){
							str=pojo.getJkid();
						}else{
							str=str+","+pojo.getJkid();
						}
					}
				}

				if(!str.isEmpty()){
					Intent intent = new Intent(getActivity(), InvestPersonPayActivity.class);
					intent.putExtra("jkid",str);
					startActivity(intent);
				}

			}
		});
		filter = (LinearLayout) view.findViewById(R.id.filter);
		empty = (ImageView) view.findViewById(R.id.emptys);

		money_select = (TextView) view.findViewById(R.id.money_select);
		sex_select = (TextView) view.findViewById(R.id.sex_select);
		view.findViewById(R.id.sex_linear).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						ActionSheetDialog dialog = new ActionSheetDialog(
								getActivity());
						dialog.builder();
						dialog.setCancelable(false);
						dialog.setCanceledOnTouchOutside(false);
						dialog.addSheetItem("全部", SheetItemColor.GRAY,
								new ActionSheetDialog.OnSheetItemClickListener() {

									@Override
									public void onClick(int which) {
										// TODO Auto-generated method stub
										sex_select.setText("全部");
										sexperson="";
										initData(minmoney,maxmoney,sexperson);
									}
								});
						dialog.addSheetItem("男", SheetItemColor.GRAY,
								new ActionSheetDialog.OnSheetItemClickListener() {

									@Override
									public void onClick(int which) {
										// TODO Auto-generated method stub
										sex_select.setText("男");
										sexperson="1";
										initData(minmoney,maxmoney,sexperson);
									}
								});
						dialog.addSheetItem("女", SheetItemColor.GRAY,
								new OnSheetItemClickListener() {
									@Override
									public void onClick(int which) {
										// TODO Auto-generated method stub
										sex_select.setText("女");
										sexperson="0";
										initData(minmoney,maxmoney,sexperson);
									}
								});
						dialog.show();
					}
				});
		view.findViewById(R.id.money_linear).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						ActionSheetDialog dialog = new ActionSheetDialog(
								getActivity());
						dialog.builder();
						dialog.setCancelable(false);
						dialog.setCanceledOnTouchOutside(false);
						dialog.addSheetItem("全部", SheetItemColor.GRAY,
								new OnSheetItemClickListener() {

									@Override
									public void onClick(int which) {
										// TODO Auto-generated method stub
										money_select.setText("全部");
										minmoney="";
										maxmoney="";
										initData(minmoney,maxmoney,sexperson);
									}
								});
						dialog.addSheetItem("500~1000", SheetItemColor.GRAY,
								new OnSheetItemClickListener() {

									@Override
									public void onClick(int which) {
										// TODO Auto-generated method stub
										minmoney="500";
										maxmoney="1000";
										money_select.setText("500~1000");
										initData(minmoney,maxmoney,sexperson);
									}
								});
						dialog.addSheetItem("1000~2000", SheetItemColor.GRAY,
								new OnSheetItemClickListener() {
									@Override
									public void onClick(int which) {
										// TODO Auto-generated method stub
										minmoney="1000";
										maxmoney="2000";
										money_select.setText("1000~2000");
										initData(minmoney,maxmoney,sexperson);
									}
								});
						dialog.addSheetItem("2000~5000", SheetItemColor.GRAY,
								new OnSheetItemClickListener() {
									@Override
									public void onClick(int which) {
										// TODO Auto-generated method stub
										minmoney="2000";
										maxmoney="5000";
										money_select.setText("2000~5000");
										initData(minmoney,maxmoney,sexperson);
									}
								});
						dialog.show();
					}
				});

		invest_list = (XListView) view.findViewById(R.id.invest_list);
		arrayList = new ArrayList<BorrowPersonPojo>();

		adapter = new InvestAdapter(getActivity(), arrayList,title_txt_center);
		adapter.setCheckInterface(this);
		invest_list.setAdapter(adapter);
		invest_list.setXListViewListener(this);
		invest_list.setPullLoadEnable(false);
		invest_list.setPullRefreshEnable(true);
	}

	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				// list.clear();
				curPage = 1;
				isloadMore = false;
				initData(minmoney,maxmoney,sexperson);
				onLoad();
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				curPage += 1;
				isloadMore = true;
				initData(minmoney,maxmoney,sexperson);
				onLoad();
			}
		}, 2000);
	}

	protected void onLoad() {
		invest_list.stopRefresh();
		invest_list.stopLoadMore();
		invest_list.setRefreshTime(TimeUtils.getDate());
	}
}
